<?php

namespace app\admin\controller;

use app\model\GoodsAgency;
use app\model\GoodsAudit;
use think\exception\ValidateException;
use app\model\Goods;
use app\model\Category;
use app\model\GoodsDescription;
use app\model\GoodsImage;
use app\model\GoodsSku;
use app\model\GoodsSkuValue;
use app\model\GoodsShareCharges;
use app\model\Store;
use app\model\Config;
use app\model\MemberAuthGroup;
use app\model\GoodsMemberDiscount;
use app\model\Operatingcity;
use app\model\Area;

class ServiceController extends Base
{

	function audit()
	{
        $model  = new GoodsAudit();
		$weid = weid();
		$page = input('post.page', 1, 'intval');
		$keyword = input('post.keyword', '', 'serach_in');
		$cat_id = input('post.cat_id', '', 'serach_in');
		$ptype = input('post.ptype', '', 'serach_in');
		$is_recommand = input('post.is_recommand', '', 'serach_in');
        $audit_status = input('post.audit_status','','serach_in');
        $where['weid'] = $weid;
		$query = $model->where($where);
		if (!empty($ptype)) {
			$query->where('ptype', $ptype);
		} else {
			$query->where('ptype', '>', 0);
		}
		if (!empty($this->sid)) {
			$query->where('sid', $this->sid);
		}

		if (!empty($keyword)) {
			$query->where('name', 'like', '%' . $keyword . '%');
		}

		if (!empty($cat_id)) {
			$query->where('cat_id',  $cat_id);
		}

		if (!empty($is_recommand) || $is_recommand === "0") {
			$query->where('is_recommand', $is_recommand);
		}

		if($audit_status){
            $query->where('audit_status', $audit_status);
        }

		$res = $query->order('audit_status asc')
			->paginate(getpage())
			->toArray();

		foreach ($res['data'] as &$vo) {
			$vo['image'] = toimg($vo['image']);
			if ($vo['sid'] == 0) {
				$vo['name'] = '[自营]' . $vo['name'];
			} else {
				$StoreTitle = Store::getTitle($vo['sid']);
				if (empty($StoreTitle)) {
					$vo['name'] = '[商户已被删除]' . $vo['name'];
				} else {
					$vo['name'] = '[' . $StoreTitle . ']' . $vo['name'];
				}
			}
			$vo['cat_id'] = Category::getTitle($vo['cat_id']);
			$vo['create_time'] = time_format($vo['create_time']);
			$vo['update_time'] = time_format($vo['update_time']);
		}
		$data['data'] = $res;
		if ($page == 1) {
			$data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray());
		}
		return $this->json($data);
	}

	function listUpdate()
	{
		$data = only('id,is_recommand,is_additional,status,sort');
		if (!$data['id']) throw new ValidateException('参数错误');
        GoodsAudit::update($data);
		return $this->json(['msg' => '操作成功']);
	}

	public function goodsaudit()
    {
        $model  = new GoodsAudit();
        $weid = weid();
        $page = input('post.page', 1, 'intval');
        $keyword = input('post.keyword', '', 'serach_in');
        $cat_id = input('post.cat_id', '', 'serach_in');
        $ptype = input('post.ptype', '', 'serach_in');
        $is_recommand = input('post.is_recommand', '', 'serach_in');
        $audit_status = input('post.audit_status','','serach_in');
        $where['weid']  = $weid;
        $where['ptype'] = 1;
        $query = $model->where($where);

        if (!empty($this->sid)) {
            $query->where('sid', $this->sid);
        }

        if (!empty($keyword)) {
            $query->where('name', 'like', '%' . $keyword . '%');
        }

        if (!empty($cat_id)) {
            $query->where('cat_id',  $cat_id);
        }

        if (!empty($is_recommand) || $is_recommand === "0") {
            $query->where('is_recommand', $is_recommand);
        }

        if($audit_status){
            $query->where('audit_status', $audit_status);
        }

        $res = $query->order('sort asc,id desc')
            ->paginate(getpage())
            ->toArray();

        foreach ($res['data'] as &$vo) {
            $vo['image'] = toimg($vo['image']);
            if ($vo['sid'] == 0) {
                $vo['name'] = '[自营]' . $vo['name'];
            } else {
                $StoreTitle = Store::getTitle($vo['sid']);
                if (empty($StoreTitle)) {
                    $vo['name'] = '[商户已被删除]' . $vo['name'];
                } else {
                    $vo['name'] = '[' . $StoreTitle . ']' . $vo['name'];
                }
            }
            $vo['cat_id'] = Category::getTitle($vo['cat_id']);
            $vo['create_time'] = time_format($vo['create_time']);
            $vo['update_time'] = time_format($vo['update_time']);
        }
        $data['data'] = $res;
        if ($page == 1) {
            $data['field_data']['cidarray'] = _generateSelectTree(Category::getpcarray());
        }
        return $this->json($data);
    }

	public function update()
	{
		$id = request()->post('id');
		$data = input('post.');
		$data['update_time'] = time();
		$data['image'] = $data['images'][0]['url'];
        $goods_moel  = new GoodsAudit();

        if(empty($data['audit_status'])){
            throw new ValidateException('请选择审核状态');
        }
        $goodsInfo = $goods_moel->where(['id'=>$id,'audit_status'=>1])->find();
        if(!$goodsInfo){
            throw new ValidateException('数据不存在或已被审核');
        }
        $goodsInfo->audit_time   = time();
        $goodsInfo->audit_status = $data['audit_status'];
        if($data['audit_status'] == 3){
            if(empty($data['reason'])){
                throw new ValidateException('请填写驳回原因');
            }
            try {
                $goodsInfo->reason       = $data['reason'];
                $goodsInfo->audit_time   = time();
                $goodsInfo->save();
            } catch (\Exception $e) {
                throw new ValidateException($e->getMessage());
            }
            return $this->json(['msg' => '操作成功']);
        }

		if ($data['cat_id']) {
			$cat = Category::find($data['cat_id']);
			if (!empty($cat)) {
				$cat = $cat->toArray();
			}
			$data['ptype'] = $cat['ptype'];
			$data['deliverymode'] = $cat['deliverymode'];
		}
		if (!empty($data['videourl'])) {
			$data['videotype'] = 1;
		} elseif (!empty($data['videoid'])) {
			$data['videotype'] = 2;
		} else {
			$data['videotype'] = 0;
		}


			$data['weid'] = weid();
			$data['create_time'] = time();

			if (!empty($this->sid)) {
				$data['sid'] = $this->sid;

				$storemod = Store::find($this->sid);
				if ($storemod) {
					$data['province_name'] = $storemod->province_name;
					$data['city_name'] = $storemod->city_name;
					$data['district_name'] = $storemod->district_name;
				}
			}
        $data['ocid'] = $goodsInfo['ocid'];
        $ocmod = Operatingcity::find($data['ocid']);
        if ($ocmod) {
            $data['province_name'] = $ocmod->province_name;
            $data['city_name'] = $ocmod->city_name;
            $data['district_name'] = $ocmod->district_name;
        }
			if (empty($data['tel'])) {
				$data['tel'] = '';
			}
			try {
			    if(empty($goodsInfo['goods_id'])){
			        unset($data['id']);
                    $res = Goods::create($data);
                    if ($res->id && empty($data['sort'])) {
                        Goods::update(['sort' => $res->id, 'id' => $res->id]);
                    }
                    $goodsInfo->goods_id = $res->id;
                }else{
			        $data['id'] = $goodsInfo['goods_id'];
			        unset($data['audit_status'],$data['reason']);
                    Goods::update($data);
                    $goodsInfo->goods_id = $data['id'];
                }
                $goodsInfo->reason   = '';
                $goodsInfo->save();
				$data['id'] = $res->id;
				$this->_synupdata($data);
			} catch (\Exception $e) {
				throw new ValidateException($e->getMessage());
			}
			return $this->json(['msg' => '操作成功', 'data' => $res->id]);
	}

	function _synupdata($data)
	{
		//详情
		if (empty(GoodsDescription::where('goods_id', $data['id'])->find())) {
			GoodsDescription::create([
				'goods_id' => (int) $data['id'],
				'description' => $data['description']
			]);
		} else {
			GoodsDescription::where('goods_id', $data['id'])->update(['description' => $data['description']]);
		}

		//sku

		GoodsSku::where('goods_id', $data['id'])->delete();
		if (isset($data['attribute'])) {
			foreach ($data['attribute'] as $attr) {
				GoodsSku::create([
					'goods_id' => (int) $data['id'],
					'name' => $attr['name'],
					'ptype' => 'radio',
					'item' =>  implode(',', $attr['item'])
				]);
			}
		}

		GoodsSkuValue::where('goods_id', $data['id'])->delete();
		if (isset($data['sku'])) {
			foreach ($data['sku'] as $skuarr) {
				GoodsSkuValue::create([
					'goods_id' => (int) $data['id'],
					'sku' => $skuarr['sku'],
					'image' => $skuarr['image'],
					'quantity' => $skuarr['quantity'],
					'price' => $skuarr['price']
				]);
			}
		}

		GoodsShareCharges::where('goods_id', $data['id'])->delete();
		if (!empty($data['is_share_charges']) && !empty($data['sharecharges'])) {
			foreach ($data['sharecharges'] as $scvo) {
				if ($scvo['price'] > 0) {
					GoodsShareCharges::create([
						'goods_id' => (int) $data['id'],
						'level' => $scvo['level'],
						'price' => (float) $scvo['price'],
						'charges_method' => (int) $data['charges_method']
					]);
				}
			}
		}

		GoodsMemberDiscount::where('goods_id', $data['id'])->delete();
		if (!empty($data['is_member_discount']) && !empty($data['MemberGroup'])) {
			foreach ($data['MemberGroup'] as $mgvo) {
				if ($mgvo['price'] > 0) {
					GoodsMemberDiscount::create([
						'goods_id' => (int) $data['id'],
						'mgid' => (int) $mgvo['id'],
						'price' => (float) $mgvo['price']
					]);
				}
			}
		}
		//图片
		GoodsImage::where('goods_id', $data['id'])->delete();
		if (isset($data['images'])) {
			foreach ($data['images'] as $image) {
				GoodsImage::create([
					'goods_id' => (int) $data['id'],
					'weid' => weid(),
					'image' => $image['url']
				]);
			}
		}
	}

	function getgoodssku()
	{
		$id =  $this->request->post('id', '', 'serach_in');
		$data['attribute'] = GoodsSku::get_goods_sku($id);
		$data['sourceAttribute'] = $data['attribute'];
		return $this->json(['data' => $data]);
	}

	function getInfo()
	{
		$id =  $this->request->post('id', '', 'serach_in');
        $model  = new GoodsAudit();
		if ($id) {
			$data = $model->field('*')->find($id)->toArray();
		} else {
			$data = [
				'is_times' => 0,
				'sort' => 100,
				'status' => 1,
			];
		}

		$GD = GoodsDescription::where(['goods_id' => $id])->find();

		if (!empty($GD)) {
			$data['description'] = $GD->description;
		}

		$goods_image = GoodsImage::where(['goods_id' => $data['goods_id']])
			->field('image')
			->order('id asc')
			->select()->toArray();

		if (!empty($goods_image)) {
			foreach ($goods_image as $key => $vo) {
				$data['images'][$key]['url'] = toimg($vo['image']);
			}
		}

		$data['attribute'] = GoodsSku::get_goods_sku($id);
		$data['sourceAttribute'] = $data['attribute'];

		$MGDiscountarray = GoodsMemberDiscount::where(['goods_id' => $id])->select()->toArray();

		if (!empty($MGDiscountarray)) {
			$MGDiscount = [];
			foreach ($MGDiscountarray as $vo) {
				$MGDiscount[$vo['mgid']] = $vo['price'];
			}
		}

		$data['MemberGroup'] = MemberAuthGroup::getGroup();
		foreach ($data['MemberGroup'] as &$mvo) {
			if (!empty($MGDiscount[$mvo['id']])) {
				$mvo['price'] = $MGDiscount[$mvo['id']];
			}
		}


		$data['sku'] = GoodsSkuValue::field('sku,image,quantity,price')->where(['goods_id' => $id])
			->order('id asc')
			->select()->toArray();

		$data['sharelevel'] = (int) Config::getconfig('agent')['level'];

		$sharechargesarray = GoodsShareCharges::where(['goods_id' => $id])->select()->toArray();

		if (!empty($sharechargesarray)) {
			foreach ($sharechargesarray as $vo) {
				$sharecharges[$vo['level']]['price'] = $vo['price'];
			}
		}

		for ($i = 1; $i <= $data['sharelevel']; $i++) {
			$data['sharecharges'][$i]['price'] = $sharecharges[$i]['price'];
			$data['sharecharges'][$i]['level'] = $i;
			if ($i == 1) {
				$data['sharecharges'][$i]['title'] = '一层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：一层为顾客的直接上级（如果开启分销内购,分销商自己购买商品，享受一层佣金）';
			}
			if ($i == 2) {
				$data['sharecharges'][$i]['title'] = '二层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：二层为顾客的上上级';
			}
			if ($i == 3) {
				$data['sharecharges'][$i]['title'] = '一层佣金';
				$data['sharecharges'][$i]['help_block'] = '注：三层为顾客的上上上级';
			}
		}

		return $this->json(['data' => $data]);
	}

	function delete()
	{
		$idx =  $this->request->post('id', '', 'serach_in');
		if (!$idx) throw new ValidateException('参数错误');
		Goods::destroy(['id' => explode(',', $idx)], true);
		return $this->json(['msg' => '操作成功']);
	}
	function getField()
	{
		$ptype = input('post.ptype');
		$data['cidarray'] = _generateSelectTree(Category::getpcarray($ptype));
		return $this->json(['data' => $data]);
	}


    function plaudit(){
        $idx =  $this->request->post('id', '', 'serach_in');
        if (!$idx) throw new ValidateException('参数错误');
        $status =  $this->request->post('status');
        $reason = input('reason');
        $goods_data =  GoodsAudit::where(['id' => explode(',', $idx),'audit_status'=>1])->select();
        foreach ($goods_data as $k=>$v){
            if($status == 3){
                $v->audit_status       = 3;
                $v->reason       = $reason;
                $v->audit_time   = time();
                $v->save();
            }else{
                $data = $v->toArray();
                if(empty($v['goods_id'])){
                    unset($v['id']);
                    $res = Goods::create($v);
                    if ($res->id && empty($v['sort'])) {
                        Goods::update(['sort' => $res->id, 'id' => $res->id]);
                    }
                    $v->goods_id = $res->id;
                }else{
                    unset($data['audit_status'],$data['reason'],$data['id'],$data['goods_id']);
                    $res = Goods::where(['id'=>$v['goods_id']])->update($data);
                }
                $v->reason   = '';
                $v->audit_status   = 2;
                $v->save();
                $data['id'] = $res->id;
                $this->_synupdata($data);
            }
        }
        return $this->json(['msg' => '操作成功']);
    }
}
